package com.example.mall.controller;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.mall.common.Result;
import com.example.mall.domain.entity.Image;
import com.example.mall.service.ImageService;
import com.example.mall.utils.MinioUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Objects;

/**
 * 功能: 文件上传
 * 作者: 沙琪马
 * 日期: 2025/3/1 20:26
 */
@RestController
@Tag(name = "文件上传")
@RequestMapping("/api/image")
@Slf4j
public class MinioFileUploadController {

    @Resource
    private MinioUtils minioUtils;

    @Resource
    private ImageService imageService;

    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public Result<Image> uploadFile(@RequestParam("file") MultipartFile file, String md5) {
        LambdaQueryWrapper<Image> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Image::getFileMd5, md5);
        Image image = imageService.getOne(wrapper);
        if(Objects.isNull(image)){
            String uuid = UUID.fastUUID().toString();
            minioUtils.upload(file, uuid);
            image = Image.builder()
                    .fileName(uuid)
                    .fileSize(String.valueOf(file.getSize()))
                    .fileMd5(md5)
                    .filePath(minioUtils.getFileUrl(uuid))
                    .contentType(file.getContentType())
                    .build();
            imageService.save(image);
        }
        return Result.success(image);
    }

    /**
     * @param fileName 文件名称
     * @Description dowload文件
     */
    @GetMapping("/dowload")
    @Operation(summary = "下载文件")
    public ResponseEntity dowloadFile(@RequestParam("fileName") String fileName) {
        return minioUtils.download(fileName);
    }


    /**
     * @param fileName 文件名称
     * @Description 得到文件url
     */
    @GetMapping("/getUrl")
    @Operation(summary = "得到文件url")
    public Result getFileUrl(@RequestParam("fileName") String fileName) {
        HashMap map = new HashMap();
        map.put("FileUrl", minioUtils.getFileUrl(fileName));
        return Result.success(map);
    }

}